package yue.shen.android.demo.net

import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.util.Log
import org.greenrobot.eventbus.EventBus

class NetworkCallbackImpl : ConnectivityManager.NetworkCallback() {


    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "0"))
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "-1"))
    }

    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "0"))
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "1"))
            } else {
                EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "2"))
            }
        } else {
            Log.i("NetworkCallbackImpl", "onCapabilitiesChanged:网络状态不可用")
            EventBus.getDefault().post(NetworkStatusEvent(network.toString(), "-1"))
        }
    }

}